from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import mail

from models import TaskModel, UserModel, GroupModel, UserGroupModel, MessageModel

from models import str2date

from django.utils import simplejson

import datetime



class MyRequestHandler(webapp.RequestHandler):
    
    def checkLogin(self):
        login = self.request.get('login')
        self.userModel = UserModel.getUser(login)
        if self.userModel:   
            return True
        else:
            self.response.headers['Content-Type'] = 'plain/text'
            self.response.out.write(self.createJsonError("unauthenticated"))     
            
    def createJsonError(self, message=""):
        return simplejson.dumps({"status": "error", "message":message})
    
    def createJsonResult(self, message="", data=""):
        return simplejson.dumps({"status": "success", "message":message, "data":data})
            
                
    
    
class UserCreate(MyRequestHandler):
    def post(self):
        nick  = self.request.get('nick')
        
        if len(nick) == 0:
            self.response.out.write(self.createJsonError("nick is empty"))
            return 
            
        if(not UserModel.nickIsUnique(nick)):
            self.response.out.write(self.createJsonError("nick is not unique")) 
            return
        try:
            user = UserModel(
                            nick = nick,
                            fullname = self.request.get('fullname'),
                            description = self.request.get('description'),
                            password = self.request.get('password'),             
            )
            user.put();
            self.response.out.write(self.createJsonResult("created")) 
        except:
            self.response.out.write(self.createJsonError("value(s) not valid"))  
            
class UsersGet(MyRequestHandler):
    def post(self):
        
        users = UserModel.all()
        self.response.out.write(self.createJsonResult(data=[p.to_dict() for p in users]))
        
        
        
        
      
    
class GroupCreate(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        
        name  = self.request.get('name')
        
        if len(name) == 0:
            self.response.out.write(self.createJsonError("name is empty"))
            return 
            
        if(not GroupModel.nameIsUnique(name)):
            self.response.out.write(self.createJsonError("name is not unique")) 
            return
        try:
            group = GroupModel(
                            name = name,
                            description = self.request.get('description'),
                            github = self.request.get('github')              
            )
            if(len(self.request.get('deadline')) >0):
                group.deadline = str2date(self.request.get('deadline'))
                
            group.put();
            relation = UserGroupModel(user=self.userModel, group=group, role="manager").put()

            
            self.response.out.write(self.createJsonResult("created", data=group.to_dict())) 
        except Exception, e:
            self.response.out.write(self.createJsonError("value(s) not valid")) 
            
class GroupsGet(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        
        groups = UserGroupModel.all().filter('user', self.userModel)
        list = []
        for p in groups:
            try:
                d = p.group.to_dict()
                d["role"] = p.role
                list.append(d)
            except:
                pass
        
        self.response.out.write(self.createJsonResult(data=list))
        
     
class GroupJoin(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        try:
            name = self.request.get('name')
            group = GroupModel.all().filter('name', name).get()
            
            check = UserGroupModel.all().filter("user", self.userModel).filter("group", group).get()
            if(check):
                self.response.out.write(self.createJsonError("This user in member this group!")) 
                return    
            
            relation = UserGroupModel(group=group, user=self.userModel, role="none")
            relation.put()
            #self.response.out.write(self.createJsonResult("joined", data=simplejson.dumps(group.to_dict()))) 
            self.response.out.write(self.createJsonResult("joined")) 
        except:
            self.response.out.write(self.createJsonError())     
        
        
class GroupUsers(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        try:
            key = self.request.get('key')
            group = GroupModel.get(key)
            
            users = UserGroupModel.all().filter("group", group)
            list = []
            check = False
            for u in users:
                try:
                    d = u.user.to_dict()
                    d["role"] = u.role
                    list.append(d)
                    if(u.user.nick == self.userModel.nick and u.role != "none"):
                        check = True
                except:
                    pass
                
            if not check:
                self.response.out.write(self.createJsonError("user is not member this group")) 
                return
            self.response.out.write(self.createJsonResult(data=list))
            
        except:
            self.response.out.write(self.createJsonError())  
            
            
class GroupDelete(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        try:
            key = self.request.get('key')
            group = GroupModel.get(key)
            
            check = UserGroupModel.all().filter("user", self.userModel).filter("group", group).get()
            if(check.role != "manager"):
                self.response.out.write(self.createJsonError("User is not manager this group!")) 
                return 
            
            delete_groups = UserGroupModel.all().filter("group", group).filter("user", self.userModel)
            for dg in delete_groups:
                dg.delete()
            
            group.delete()
            self.response.out.write(self.createJsonResult("deleted")) 
        except:
            self.response.out.write(self.createJsonError())  
            
        
class GroupAcceptUser(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        try:
            key = self.request.get('key')
            group = GroupModel.get(key)
                
                
            check = UserGroupModel.all().filter("group", group).filter("user", self.userModel).get()
            if not check:
                self.response.out.write(self.createJsonError("current is not manager this group")) 
                return
            if(check.role != "manager"):
                self.response.out.write(self.createJsonError("current user is not manager this group")) 
                return
                    
            user = UserModel.getUser(self.request.get('nick'))
            relation = UserGroupModel.all().filter("group", group).filter("user", user).get()
            if not relation:
                self.response.out.write(self.createJsonError("user is not member this group")) 
                return
            if(relation.role == "none"):                
                relation.role = "developer"
                relation.put()
                self.response.out.write(self.createJsonResult("accepted")) 
            else:
                self.response.out.write(self.createJsonError("user is member (developer or manager) this group")) 
                return
        except:
            self.response.out.write(self.createJsonError())  
            
                  

     
class TasksGet(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        try:
            group_key = self.request.get('group_key')
            group = GroupModel.get(group_key)
            
            if not group:
                self.response.out.write(self.createJsonError("group not exists")) 
                return
            
            if not group.userIsMember(self.userModel):        
                self.response.out.write(self.createJsonError("current user is not a manager or developer this group")) 
                return
            
            tasks = TaskModel.all().filter("group", group)
            self.response.out.write(self.createJsonResult(data=[p.to_dict() for p in tasks]))
        except:
            self.response.out.write(self.createJsonError())  
        
        
class TaskCreate(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return

        
        try:
            group_key = self.request.get('group_key')
            group = GroupModel.get(group_key)
            user = UserModel.getUser(self.request.get('nick'));
            
            if len(self.request.get('parent')) > 0:
                parent = TaskModel.get(self.request.get('parent'))
            else:
                parent = None
            
                    
            if not group:
                self.response.out.write(self.createJsonError("group not exists")) 
                return
                
            if not group.userIsMember(self.userModel):        
                self.response.out.write(self.createJsonError("current user is not a manager or developer this group")) 
                return
            
            task = TaskModel(
                    name = self.request.get('name'),
                    description = self.request.get('description'),
                    deadline = str2date(self.request.get('deadline')),
                    group = group,
                    user = user,
                    parent_task = parent,
            )
                        
            if(self.request.get('checked') == "True"):
                task.checked = True;
            else:
                task.checked = False
                    
            task.put();
            self.response.headers['Content-Type'] = 'plain/text'
            self.response.out.write(self.createJsonResult("created", data=task.to_dict()))
        except:
            self.response.out.write(self.createJsonError())
            
class TaskSetChecked(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return

        
        try:
            task_key = self.request.get('task_key')
            task = TaskModel.get(task_key)
        
            
                    
            if not task:
                self.response.out.write(self.createJsonError("task not exists")) 
                return
                
            
                        
            if(self.request.get('checked') == "True"):
                task.checked = True;
            else:
                task.checked = False
                    
            task.put();
            self.response.headers['Content-Type'] = 'plain/text'
            self.response.out.write(self.createJsonResult("updated", data=task.to_dict()))
        except:
            self.response.out.write(self.createJsonError())      
            
            
class MessageCreate(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return

        
        try:
            group_key = self.request.get('group_key')
            group = GroupModel.get(group_key)
            #user = UserModel.getUser(self.request.get('to'));
            
            
                    
            if not group:
                self.response.out.write(self.createJsonError("group not exists")) 
                return
                
            if not group.userIsMember(self.userModel):        
                self.response.out.write(self.createJsonError("current user is not a manager or developer this group")) 
                return
            
            members = UserGroupModel.all().filter("group", group)
            for member in members:
                message = MessageModel(
                        sender = self.userModel,
                        recipient = member.user,
                        group = group,
                        title = self.request.get('title'),
                        text = self.request.get('text'),
                )
                message.put();
                        
                    
            self.response.headers['Content-Type'] = 'plain/text'
            self.response.out.write(self.createJsonResult("created",))
        except:
            self.response.out.write(self.createJsonError())  
            
            
class MessagesGet(MyRequestHandler):
    def post(self):
        if (not self.checkLogin()):
            return
        try:
            group_key = self.request.get('group_key')
            group = GroupModel.get(group_key)
            
            if not group:
                self.response.out.write(self.createJsonError("group not exists")) 
                return
            
            if not group.userIsMember(self.userModel):        
                self.response.out.write(self.createJsonError("current user is not a manager or developer this group")) 
                return
            
            messages = MessageModel.all().filter("group", group).filter("recipient", self.userModel)
            self.response.out.write(self.createJsonResult(data=[p.to_dict() for p in messages]))
        except:
            self.response.out.write(self.createJsonError())   
            
        
     
    
    

    